<template>
  <div class="add-field-module">
    <el-dialog
      v-loading="loading"
      :visible.sync="dialogVisible"
      :show-close="false"
      :append-to-body="true"
      :class="{'mobile-el-dialog': showMobilePage}"
      class="add-field-dialog medium-common-dialog-size"
      width="55%"
      @closed="handleClose"
    >
      <Title title="批量导入字段" font-size="16px" style="margin: 0 0 24px"/>
      <div class="on-cell" style="margin-bottom: 20px">
        <div class="create-field-module" style="margin: 0">
          <el-form v-if="!isNeedBaseFiled" ref="editFieldForm" :model="dataForm" :rules="formRules" class="el-form-box-left" label-width="85px">
            <el-form-item label="字段分类" prop="categoryId" class="client-type" style="margin-bottom:0px;">
              <el-select v-model="dataForm.categoryId" popper-class="global-select-down" name="categoryId">
                <el-option
                  v-for="item in categoryList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id" />
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        <ImportBtn
          v-if="!showMobilePage"
          :hide-confirm="true"
          :radio-list="radioList"
          :import-api="importApi"
          :is-need-base-filed="isNeedBaseFiled"
          btn-text="导入数据"
          style="margin-right: 10px;"
          @onGetList="onSucess"/>
      </div>
      <ImportBtn
        v-if="showMobilePage"
        :hide-confirm="true"
        :radio-list="radioList"
        :import-api="importApi"
        :is-need-base-filed="isNeedBaseFiled"
        btn-text="导入数据"
        style="margin-bottom: 10px;"
        @onGetList="onSucess"/>
      <div class="file-list">
        <el-tag
          v-for="(tag, index) in fileName"
          :key="index"
          class="tag"
          closable
          @close="deleteTable(tag)">
          {{ tag }}
        </el-tag>
      </div>
      <div class="transfer-container transfer-diy-empty">
        <treeTransfer
          ref="transfer"
          :to_data="transferData"
          :from_data="fieldListArr"
          :button_text="['加入右侧','加入左侧']"
          :title="['数据表字段','目标导入字段']"
          :empty-text="'2'"
          @removeBtn="fieldChange"
          @addBtn="fieldChange"
        />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="ok" type="primary" @click="handelOk">保存</el-button>
        <el-button class="cancel" @click="dialogVisible = false">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import ImportBtn from '../importField';
import treeTransfer from 'el-tree-transfer';
import { mapState } from 'vuex';
// import { saveTempReport } from '@/api/reportManage';
import Title from '@/components/Title';
export default {
  components: { ImportBtn, treeTransfer, Title },
  props: {
    radioList: {
      type: Object,
      default: () => {
        return {};
      }
    },
    importApi: {
      type: String,
      default: '/admin/report/importTempReport'
    },
    isNeedBaseFiled: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      antiShakeTime: 0,
      categoryTabs: [],
      categoryTabsValue: 0,
      dataForm: {
        categoryId: null,
        categoryName: ''
      },
      formRules: {
        categoryId: [{ required: true, trigger: 'change, blur', message: '请选择字段分类' }]
      },
      dialogVisible: false,
      loading: false,
      transferData: [],
      fileName: [],
      fieldListArr: [],
      rightData: [],
      tempFieldListArr: []
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    ...mapState({
      'categoryList': state => state.options.fieldCategorys
    })
  },
  methods: {
    onSucess(data) {
      // 插入数据
      // const formatData = {};
      // formatData.pid = 0;
      // formatData.label = data.fileName;
      const baseLenght = this.tempFieldListArr.length;
      const children = data.fieldData.filter(item => (item !== null && !item.match(/^[ ]*$/))).map((field, index) => {
        return {
          pid: 0,
          fileName: data.fileName,
          id: index + baseLenght,
          isLast: true,
          label: field
        };
      });
      // formatData.children = children;

      // this.tempFieldListArr.push(JSON.parse(JSON.stringify(formatData)));

      // 动态添加 id 和 pid  tempFieldListArr
      this.$refs['transfer'].clearChecked();
      this.fieldListArr = [...this.fieldListArr, ...children];
      this.tempFieldListArr = [...this.tempFieldListArr, ...children];
      this.fileName.push(data.fileName);
      this.fileName = this.handelDataRepeat(this.fileName);
      try {
        this.fieldListArr = this.handelFieldDataRepeat(this.fieldListArr);
      } catch (e) {
        console.log(e);
      }
    },
    // 去重
    handelDataRepeat(array) {
      var arrs = [];
      // 遍历当前数组
      for (var i = 0; i < array.length; i++) {
        // 如果临时数组里没有当前数组的当前值，则把当前值push到新数组里面
        if (arrs.indexOf(array[i]) === -1) {
          arrs.push(array[i]);
          // }
        }
      }
      return arrs;
    },
    handelFieldDataRepeat(array) {
      var arrs = [];
      var labels = [];
      // 遍历当前数组
      for (var i = 0; i < array.length; i++) {
        // 如果临时数组里没有当前数组的当前值，则把当前值push到新数组里面
        if (labels.indexOf(array[i].label) < 0) {
          labels.push(array[i].label);
          arrs.push(array[i]);
        }
      }
      return arrs;
    },
    fieldChange(leftData, rightData, item) {
      this.fieldListArr = leftData;
      this.rightData = rightData;
      this.transferData = rightData;
    },
    deleteTable(item) {
      this.fileName = this.fileName.filter(i => {
        return i !== item;
      });
      this.fieldListArr = this.fieldListArr.filter(i => {
        return i.fileName !== item;
      });
      this.rightData = this.rightData.filter(i => {
        return i.fileName !== item;
      });
      this.transferData = this.transferData.filter(i => {
        return i.fileName !== item;
      });
      // if (this.fieldListArr.length === 0) {
      this.$refs['transfer'].clearChecked();
      // }
    },
    async handelOk() {
      var timestamp = new Date().getTime();
      if (timestamp - this.antiShakeTime < 500) {
        return;
      }
      this.antiShakeTime = timestamp;
      const rightData = this.rightData;
      if (rightData && rightData.length) {
        const fieldNameList = rightData;
        this.$refs['editFieldForm'].validate((valid) => {
          if (valid) {
            if (fieldNameList.length === 0) {
              this.$message({ type: 'warning', message: '请选添加字段' });
            } else {
              this.$emit('onSuccess', { params: fieldNameList, categoryId: this.dataForm.categoryId });
            }
          } else {
            this.$message({ type: 'warning', message: '请选择字段分类' });
          }
        });
      } else {
        this.$message({
          type: 'warning',
          message: '请选择字段'
        });
      }
    },
    addCategoryTab() {
      if (this.dataForm.categoryName === '') return;
      this.categoryTabs.push(this.dataForm.categoryName);
      // this.categoryTabs = this.handelDataRepeat(this.categoryList);
    },
    categoryChange(item) {
      this.dataForm.categoryName = item.name;
      this.dataForm.categoryId = item.id;
    },
    removeTab() {

    },
    handleClose() {
      this.dataForm.categoryId = '';
      this.fileName = [];
      this.rightData = [];
      this.fieldListArr = [];
      this.transferData = [];
      this.tempFieldListArr = [];
    },
    handleRepeatField(repeats) {
      this.rightData = this.rightData.filter(item => {
        return repeats.indexOf(item.label) < 0;
      });
      this.transferData = this.rightData;
    }
  }
};
</script>
<style lang="scss" scoped>
.on-cell {
  display: flex;
  justify-content: space-between;
}
.add-botton {
  margin-left: 10px;
}
.file-list {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  .tag {
    margin-right: 10px;
    margin-bottom: 10px;
  }
}
.transfer {
  height: 348px !important;
  width: 568px !important;
}
.dialog-footer {
  display: flex;
  justify-content: center;
  .ok {
    width: 120px;
    font-size: 14px;
  }
  .cancel {
    width: 80px;
    font-size: 14px;
    color: #406EFF;
    background:rgba(239,243,251,1);
    border: none;
  }
}
.mobile-el-dialog {
  ::v-deep {
    .el-select {
      width: 100%;
      .el-input__inner {
        width: 100%;
      }
    }
  }
  .transfer-container {
    overflow-x: auto;
  }
}
</style>
